package com.siecom.transport.handler;

import android.os.Bundle;
import android.util.Log;

import com.siecom.algorithm.sm.SM2;
import com.siecom.algorithm.sm.SMUtil;
import com.siecom.constconfig.ConstDefine;
import com.siecom.constconfig.ErrorDefine;
import com.siecom.framework.device.SiecomDevice;
import com.siecom.framework.device.SiecomTask;
import com.siecom.hostservice.MainActivity;
import com.siecom.module.DeviceCallback;
import com.siecom.module.DeviceInterface;
import com.siecom.proto.Message;
import com.siecom.tool.ByteTool;
import com.siecom.tool.LogUtil;
import com.siecom.transport.CommServer;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by zhq on 2017/1/18.
 */

public class KeyBoardHandler implements ServiceHandler {
    private static final String TAG = "KeyBoardHandler";
    private CommServer server;
    private int step = 0;
    private int passVoice = 0;
    public static boolean plainTextInputing = true;
    @Override
    public void onReceive(CommServer server, Message.siecomproto msg,String message) {
        Log.e("KeyBoardHandler", "onReceive");
        this.server = server;
        switch (msg.getCmd()){
            case ConstDefine.INPUT_MAIN_REQUEST:
                inputMainKey(msg);
                break;
            case ConstDefine.INPUT_WORK_REQUEST:
                inputWorkKey(msg);
                break;
            case ConstDefine.SM2_NEW_KEY_PAIR:
                sm2NewKeyPair(msg);
                break;
            case ConstDefine.INPUT_KEY_REQUEST:
                startInputPwd(msg);
                break;

                //用传入的公钥 加密随机主密钥 并写入主密钥
            case ConstDefine.SM2_RSA_MAINKEY_REQUEST:
                pubKeyEncryptMainKey(msg);
                break;
                //重置秘钥
            case ConstDefine.RESET_KEYBOARD_REQUEST:
                resetKeyBorad(msg);
                break;
                //明文转密文
            case ConstDefine.TMK_DECRYPT_REQUEST:
                getEncrypteData(msg);
                break;
            case ConstDefine.SET_ENCRYPT_REQUEST:
                setEncrypt(msg);
                break;

            case ConstDefine.KEYBOARD_CANCEL_REQUEST:
                cancelKeyBoard(msg);
                break;

            case ConstDefine.CALCMAC_REQUEST:
                calcMac(msg);
                break;

        }
    }

    //重置密钥
    private  void  resetKeyBorad(Message.siecomproto msg){
        byte zero16[] = new byte[16];
        SiecomDevice.inputMainKey(10, zero16, new SiecomTask.TaskCallback() {
            @Override
            public void onStart(Bundle bundle) {

            }

            @Override
            public void onSucceed(Bundle bundle) {
                SiecomDevice.inputWorkKey(10, 10, zero16, new SiecomTask.TaskCallback() {
                    @Override
                    public void onStart(Bundle bundle) {

                    }

                    @Override
                    public void onSucceed(Bundle bundle) {
                        com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                        msgBuilder.setModule(ConstDefine.KEY_MODULE);
                        msgBuilder.setMsgid(msg.getMsgid());
                        msgBuilder.setCmd(msg.getCmd() + 1);
                        msgBuilder.setError(0);
                        com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                        server.sendToRemote(respondMsg);
                    }

                    @Override
                    public void onError(Bundle bundle) {
                        com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                        msgBuilder.setModule(ConstDefine.KEY_MODULE);
                        msgBuilder.setMsgid(msg.getMsgid());
                        msgBuilder.setCmd(msg.getCmd() + 1);
                        msgBuilder.setRespond(bundle.getString("msg"));
                        msgBuilder.setError(bundle.getInt("code"));
                        com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                        server.sendToRemote(respondMsg);
                    }
                });
            }

            @Override
            public void onError(Bundle bundle) {
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setRespond(bundle.getString("msg"));
                msgBuilder.setError(bundle.getInt("code"));
                com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        });
    }
    //使用公钥加密随机主密钥 并写入主密钥
    private  void  pubKeyEncryptMainKey(Message.siecomproto msg){
        JSONObject json = null;
        int MainKeyIndex = 0;
        int pukType = 1; // 公钥类型 0--RSA， 1--SM2
        String pukkeyData  = "";
        int sessionKeyType = 4;  //1——DES 单倍长 2 —— DES 双倍长 3—— DES 三倍长  4 —— SM4(16位  32个字符)
        try {
            json = new JSONObject(msg.getRequest());
            MainKeyIndex = json.getInt("mainKeyIndex");
            pukType = json.getInt("pubKeyType");
            pukkeyData = json.getString("pubKeyData");
            sessionKeyType = json.getInt("sessionKeyType");
        } catch (JSONException e) {
            e.printStackTrace();

        }
        String mainkey = SiecomDevice.getRandom32();
        LogUtil.e(TAG,"getRandom32 main == " + mainkey);
        if(pukType == 1){ //国密 SM2
            SiecomDevice.sm2EnDecryptMainKey(pukkeyData,mainkey,MainKeyIndex,
                    new SiecomTask.TaskCallback() {
                @Override
                public void onStart(Bundle bundle) {

                }

                @Override
                public void onSucceed(Bundle bundle) {
                    JSONObject json = new JSONObject();
                    try {
//                        json.put("code",bundle.getInt("code"));
                        json.put("data", bundle.getString("data"));
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(ConstDefine.SM2_RSA_MAINKEY_RESPOND);
                    msgBuilder.setError(0);
                    msgBuilder.setRespond(json.toString());
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);
                }

                @Override
                public void onError(Bundle bundle) {
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(msg.getCmd() + 1);
                    msgBuilder.setRespond(bundle.getString("msg"));
                    msgBuilder.setError(bundle.getInt("code"));
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);
                }
            });

        }else if(pukType == 0){
            SiecomDevice.rsaEnDecryptMainKey(pukkeyData,mainkey,MainKeyIndex,
                    new SiecomTask.TaskCallback() {
                        @Override
                        public void onStart(Bundle bundle) {

                        }

                        @Override
                        public void onSucceed(Bundle bundle) {
                            JSONObject json = new JSONObject();
                            try {
//                        json.put("code",bundle.getInt("code"));
                                json.put("data", bundle.getString("data"));
                            }catch (JSONException e){
                                e.printStackTrace();
                            }
                            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                            msgBuilder.setModule(ConstDefine.KEY_MODULE);
                            msgBuilder.setMsgid(msg.getMsgid());
                            msgBuilder.setCmd(ConstDefine.SM2_RSA_MAINKEY_RESPOND);
                            msgBuilder.setError(0);
                            msgBuilder.setRespond(json.toString());
                            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                            server.sendToRemote(respondMsg);
                        }

                        @Override
                        public void onError(Bundle bundle) {
                            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                            msgBuilder.setModule(ConstDefine.KEY_MODULE);
                            msgBuilder.setMsgid(msg.getMsgid());
                            msgBuilder.setCmd(msg.getCmd() + 1);
                            msgBuilder.setRespond(bundle.getString("msg"));
                            msgBuilder.setError(bundle.getInt("code"));
                            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                            server.sendToRemote(respondMsg);
                        }
                    });
        }
        else {  //暂不支持 国际形式秘钥
            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
            msgBuilder.setModule(ConstDefine.KEY_MODULE);
            msgBuilder.setMsgid(msg.getMsgid());
            msgBuilder.setCmd(msg.getCmd() + 1);
            msgBuilder.setRespond("暂不支持国际秘钥");
            msgBuilder.setError(-999);
            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
            server.sendToRemote(respondMsg);
        }


    }

    public  void calcMac(Message.siecomproto msg){
        JSONObject json = null;
        int MainKeyIndex = 0;
        int workKeyIndex  = 0;
        String data  = null;
        int macMode = 0x02;
        try {
            json = new JSONObject(msg.getRequest());
            MainKeyIndex = json.getInt("mainKeyIndex");
            workKeyIndex = json.getInt("workKeyIndex");
            data = json.getString("data");
            macMode = json.getInt("macMode");
        } catch (JSONException e) {
            e.printStackTrace();

        }
        byte[] macData = ByteTool.hexStr2Bytes(data);
        DeviceInterface.calcMAC(macMode, MainKeyIndex, workKeyIndex, macData, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setRespond(bundle.getString("message"));
                msgBuilder.setError(bundle.getInt("code"));
                com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }

            @Override
            public void onSuccess(Bundle bundle) {

                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setError(0);
                msgBuilder.setRespond(ByteTool.byte2hex(bundle.getByteArray("data")));
                com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        },false);

    }



    public void cancelKeyBoard(Message.siecomproto msg){
        plainTextInputing = false;
        DeviceInterface.cancelKeyBoardInput();
        MainActivity.closeKeyBoard();
        com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
        msgBuilder.setModule(msg.getModule());
        msgBuilder.setMsgid(msg.getMsgid());
        msgBuilder.setCmd(msg.getCmd() + 1);
        msgBuilder.setError(0);
        msgBuilder.setRespond("cancelKeyBoard");
        com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
        server.sendToRemote(respondMsg);
//        MainActivity.getmMainPci().DLL_PciGetPinExit();
        SiecomDevice.cancelLastTask(true); //取消输入
        LogUtil.e(TAG,"DLL_PciGetPinExit--" );
//        MainActivity.getmMainPci().DLL_PciKbClose(); //
//        LogUtil.e(TAG,"DLL_PciKbClose" );
        MainActivity.getmSys().DLL_SysLedControl((byte) 11,(byte)0);
    }
    public  void setEncrypt(Message.siecomproto msg){
        JSONObject json = null;
        try {
            json = new JSONObject(msg.getRequest());

            String endType = null;
            String mKeyIndex = null;
            String wKeyIndex = null;
            if(json.has("endType")){
                endType =   json.getString("endType");
            }
            if(json.has("mKeyIndex")){

                mKeyIndex = json.getString("mKeyIndex");
            }
            if(json.has("wKeyIndex")){
                wKeyIndex = json.getString("wKeyIndex");
            }

            DeviceInterface.keySetEncryptMode(json.getInt("encrypt"),endType,mKeyIndex,wKeyIndex, new DeviceCallback() {
                @Override
                public void onStart() {

                }

                @Override
                public void onError(Bundle bundle) {
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(msg.getCmd() + 1);
                    msgBuilder.setRespond(bundle.getString("message"));
                    msgBuilder.setError(bundle.getInt("code"));
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);
                }

                @Override
                public void onSuccess(Bundle bundle) {
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(msg.getCmd() + 1);
                    msgBuilder.setError(0);
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);

                }

                @Override
                public void onCompleted(Bundle bundle) {

                }
            },false);

        }catch (JSONException e) {
            e.printStackTrace();

        }

    }
    public  void  startInputPwd(Message.siecomproto msg){

        JSONObject json = null;
        String cardNo = null;
        String masterKeyIndex  = null;
        String workKeyIndex  = null;
        String timeOutSec = String.valueOf(msg.getTimeout()/1000);
        int encryptMode = 0;
        String pwdLength = null;
        int inputTimes = 1;
        try {
            json = new JSONObject(msg.getRequest());
            cardNo = json.getString("cardNo");
            if(json.has("mainKeyIndex"))
            masterKeyIndex = json.getString("mainKeyIndex");
            if(json.has("workKeyIndex"))
            workKeyIndex = json.getString("workKeyIndex");
            encryptMode = json.getInt("encryptType");
            LogUtil.e("----","加密模式：" + encryptMode);
            pwdLength = json.getString("pwdLength");
            if(json.has("passVoice")) {
                passVoice = json.getInt("passVoice");
            }
            if(json.has("inputTimes")){
                inputTimes = json.getInt("inputTimes");

            }
            LogUtil.e(TAG,"可以调用 startInputPwd 了 inputTimes==" + inputTimes);
        } catch (JSONException e) {
            e.printStackTrace();
            LogUtil.e(TAG,"加密异常:" + e.getMessage());
        }
        int keyIndex = 0;
        if(encryptMode == 1){ //国际
            encryptMode = 0x00;
            keyIndex = Integer.parseInt(workKeyIndex);
        }else if (encryptMode == 2){ //国密模式
            encryptMode = 0x00;
            keyIndex = 10 + Integer.parseInt(workKeyIndex);
        }else {
            encryptMode = 0x03; //明文
        }

        int finalEncryptMode = encryptMode;
        int timeoutS = msg.getTimeout()/1000;
        timeoutS = Math.max(10,timeoutS);
        SiecomDevice.getPin(keyIndex, cardNo, "123456.00", timeoutS,
                (byte) Integer.parseInt(pwdLength),(byte) Integer.parseInt(pwdLength), (byte) encryptMode,inputTimes,
                new SiecomTask.TaskCallback() {
                    @Override
                    public void onStart(Bundle bundle) {
                        MainActivity.showKeyBoard(passVoice);
                        // 11键盘  10指纹 9IC卡  8磁条卡  5蓝牙 6 身份证
                        MainActivity.getmSys().DLL_SysLedControl((byte) 11,(byte)1);
                    }

                    @Override
                    public void onSucceed(Bundle bundle) {

                        int flag = bundle.getInt("option");
                        if (flag == 1) {
                            int num = bundle.getInt("keyNum");
                            LogUtil.e("KeyBoardHandler", "num =" + num + "-------------flag=" + flag);
                            JSONObject json = new JSONObject();
                            try {
                                json.put("data", num);
                                json.put("flag", flag);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                            msgBuilder.setModule(ConstDefine.KEY_MODULE);
                            msgBuilder.setMsgid(msg.getMsgid());
                            msgBuilder.setCmd(msg.getCmd() + 1);
                            msgBuilder.setError(0);
                            msgBuilder.setRespond(json.toString());
                            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                            server.sendToRemote(respondMsg);
                            MainActivity.updateKeyBoard(num);

                        }

                        if(flag == 0){  //结束输入
                            byte[] pwd = bundle.getByteArray("password");
                            String data  = ByteTool.byte2hex(pwd);
                            if(finalEncryptMode == 3){
                                data = new String(pwd).trim();
                            }
                            LogUtil.e("onCompleted","data =" + data +  "-------------flag=" + flag);
                            JSONObject json = new JSONObject();
                            try {
                                json.put("flag", flag);
                                json.put("data", data);
                            }catch (JSONException e){
                                e.printStackTrace();
                            }
                            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                            msgBuilder.setModule(ConstDefine.KEY_MODULE);
                            msgBuilder.setMsgid(msg.getMsgid());
                            msgBuilder.setCmd(msg.getCmd() + 1);
                            msgBuilder.setError(0);
                            msgBuilder.setRespond(json.toString());
                            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                            server.sendToRemote(respondMsg);

                            MainActivity.closeKeyBoard();
                            MainActivity.playVoice(ConstDefine.OPERATE_SUCC);
                            MainActivity.getmSys().DLL_SysLedControl((byte) 11,(byte)0);
                        }


                    }

                    @Override
                    public void onError(Bundle bundle) {
                        MainActivity.getmSys().DLL_SysLedControl((byte) 11,(byte)0);
                        LogUtil.e("onError", "-------------" + bundle.getInt("code"));
                        if(bundle.getInt("code")== ErrorDefine.LENGTH_ERR){
                            MainActivity.keyBoardLengthERR();
                            return;
                        }
                        com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                        msgBuilder.setModule(ConstDefine.KEY_MODULE);
                        msgBuilder.setMsgid(msg.getMsgid());
                        msgBuilder.setCmd(msg.getCmd() + 1);
                        JSONObject jb = new JSONObject();
                        try {
                            jb.put("code",bundle.getInt("code"));
                            jb.put("message",bundle.getString("message"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        msgBuilder.setRespond(jb.toString());
                        msgBuilder.setError(bundle.getInt("code"));
                        com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                        server.sendToRemote(respondMsg);
                        MainActivity.closeKeyBoard();
                        MainActivity.playVoice(ConstDefine.OPERATE_FAIL);
                    }
                });

    }

    private  void  inputMainKey(Message.siecomproto msg){
        JSONObject json = null;
        String keyIndex = null;
        String keyData  = null;
        int encryptType = 1;
        int mode = 0; //0x00明文写入  0x81 解密写入(更新密钥)  0x01加密写入
        try {
            json = new JSONObject(msg.getRequest());
            keyIndex = json.getString("keyIndex");
            keyData = json.getString("keyData");
            encryptType = json.getInt("encryptType");
            mode = json.getInt("mode");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        int index = 0;
        if(encryptType == 1){
            index = Integer.parseInt(keyIndex);
        }else {
            index = 10 + Integer.parseInt(keyIndex);
        }

        if(mode == 0){  // 明文写入主密钥
            SiecomDevice.inputMainKey(index, ByteTool.hexStr2Bytes(keyData), new SiecomTask.TaskCallback() {
                @Override
                public void onStart(Bundle bundle) {
                    LogUtil.e(TAG,"inputMainKey onStart"  );
                }

                @Override
                public void onSucceed(Bundle bundle) {
                    LogUtil.e(TAG,"inputMainKey onSucceed"  );
                    JSONObject json = new JSONObject();
                    try {
                        json.put("data", bundle.getString("data"));
                    }catch (JSONException e){

                    }
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(msg.getCmd() + 1);
                    msgBuilder.setError(0);
                    msgBuilder.setRespond(json.toString());
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);
                }

                @Override
                public void onError(Bundle bundle) {
                    LogUtil.e(TAG,"inputMainKey onSucceed"  );
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(msg.getCmd() + 1);
                    msgBuilder.setRespond(bundle.getString("message"));
                    msgBuilder.setError(bundle.getInt("code"));
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);
                }
            });
        }

        if(mode == 0x81){ //0x81 解密写入(更新密钥)
            byte[] checkValue = new byte[16];
            SiecomDevice.changeMainKey(keyData, checkValue, (byte) index, new SiecomTask.TaskCallback() {
                @Override
                public void onStart(Bundle bundle) {
                    LogUtil.e(TAG,"changeMainKey onStart"  );
                }

                @Override
                public void onSucceed(Bundle bundle) {
                    LogUtil.e(TAG,"changeMainKey onSucceed"  );
                    JSONObject json = new JSONObject();
                    try {
                        json.put("data", bundle.getString("data"));
                    }catch (JSONException e){

                    }
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(msg.getCmd() + 1);
                    msgBuilder.setError(0);
                    msgBuilder.setRespond(json.toString());
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);
                }

                @Override
                public void onError(Bundle bundle) {
                    LogUtil.e(TAG,"changeMainKey onSucceed"  );
                    com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                    msgBuilder.setModule(ConstDefine.KEY_MODULE);
                    msgBuilder.setMsgid(msg.getMsgid());
                    msgBuilder.setCmd(msg.getCmd() + 1);
                    msgBuilder.setRespond(bundle.getString("message"));
                    msgBuilder.setError(bundle.getInt("code"));
                    com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                    server.sendToRemote(respondMsg);
                }
            });
        }

    }


    private  void  inputWorkKey(Message.siecomproto msg){
        JSONObject json = null;
        String MainKeyIndex = null;
        String workKeyIndex  = null;
        String keyData  = null;
        int encryptType = 1;
        int mode = 0;
        try {
            json = new JSONObject(msg.getRequest());
            MainKeyIndex = json.getString("mainKeyIndex");
            workKeyIndex = json.getString("workKeyIndex");
            keyData = json.getString("keyData");
            encryptType = json.getInt("encryptType"); //1 3des  2 sm4
            mode = json.getInt("mode"); //加密写入 解密写入
        } catch (JSONException e) {
            e.printStackTrace();

        }
        int index = 0;
        if(encryptType == 1){
            index = Integer.parseInt(workKeyIndex);
        }else if (encryptType == 2){
            index = 10 + Integer.parseInt(workKeyIndex);
        }
        assert keyData != null;
        SiecomDevice.inputWorkKey(index, index,
                ByteTool.hexStr2Bytes(keyData),
                new SiecomTask.TaskCallback() {
                    @Override
                    public void onStart(Bundle bundle) {

                    }

                    @Override
                    public void onSucceed(Bundle bundle) {
                        JSONObject json = new JSONObject();
                        try {
                            json.put("data", bundle.getString("data"));
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                        com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                        msgBuilder.setModule(ConstDefine.KEY_MODULE);
                        msgBuilder.setMsgid(msg.getMsgid());
                        msgBuilder.setCmd(msg.getCmd() + 1);
                        msgBuilder.setError(0);
                        msgBuilder.setRespond(json.toString());
                        com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                        server.sendToRemote(respondMsg);
                    }

                    @Override
                    public void onError(Bundle bundle) {
                        com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                        msgBuilder.setModule(ConstDefine.KEY_MODULE);
                        msgBuilder.setMsgid(msg.getMsgid());
                        msgBuilder.setCmd(msg.getCmd() + 1);
                        msgBuilder.setRespond(bundle.getString("message"));
                        msgBuilder.setError(bundle.getInt("code"));
                        com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                        server.sendToRemote(respondMsg);
                    }
                });

    }


    //获取加密数据
    private  void  getEncrypteData(Message.siecomproto msg){
        JSONObject json = null;
        String password = null;
        String workKeyIndex  = null;
        String account  = null;
        int encryptType = 2;

        try {
            json = new JSONObject(msg.getRequest());
            password = json.getString("password"); // 密码
            workKeyIndex = json.getString("workKeyIndex");
            account = json.getString("account"); //卡号 账号

        } catch (JSONException e) {
            e.printStackTrace();

        }
        int index = 0;
//        if(encryptType == 1){
            index = Integer.parseInt(workKeyIndex);

//        }else if (encryptType == 2){
//            index = 10 + Integer.parseInt(workKeyIndex);
//        }
        if(account.length() < 14 || password.length() < 6){
            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
            msgBuilder.setModule(ConstDefine.KEY_MODULE);
            msgBuilder.setMsgid(msg.getMsgid());
            msgBuilder.setCmd(msg.getCmd() + 1);
            msgBuilder.setRespond("账户或密码不正确");
            msgBuilder.setError(-2);
            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
            server.sendToRemote(respondMsg);
            return;
        }
        //账户号去掉最后一位 从右往左取12位
        String cardNo = account.substring(account.length()-13,account.length()-1);
        cardNo = "00000000000000000000" + cardNo;
        LogUtil.e(TAG,"cardNo == ：" + cardNo);
        String  pwd = "06" + password + "FFFFFFFFFFFFFFFFFFFFFFFF";

        byte indata[] = ByteTool.bytesXOR(ByteTool.hexStr2Bytes(cardNo),ByteTool.hexStr2Bytes(pwd));
        LogUtil.e(TAG,"账号密码异或结果为：" + ByteTool.byte2hex(indata));
        List<byte[]> list = new ArrayList<>();
        int ret = SiecomDevice.sm4EnDecryptData(index,0,1,indata,list);
        if(ret == 0){
            JSONObject json2 = new JSONObject();
            try {
                json2.put("data", ByteTool.byte2hex(list.get(0)));
            }catch (JSONException e){
                e.printStackTrace();
            }
            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
            msgBuilder.setModule(ConstDefine.KEY_MODULE);
            msgBuilder.setMsgid(msg.getMsgid());
            msgBuilder.setCmd(msg.getCmd() + 1);
            msgBuilder.setError(0);
            msgBuilder.setRespond(json2.toString());
            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
            server.sendToRemote(respondMsg);
        }else {
            com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
            msgBuilder.setModule(ConstDefine.KEY_MODULE);
            msgBuilder.setMsgid(msg.getMsgid());
            msgBuilder.setCmd(msg.getCmd() + 1);
            msgBuilder.setRespond("get password error");
            msgBuilder.setError(-1);
            com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
            server.sendToRemote(respondMsg);
        }


    }

    //国密2生成密钥对
    private void sm2NewKeyPair(Message.siecomproto msg){
        DeviceInterface.getSM2keypair(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setRespond(bundle.getString("message"));
                msgBuilder.setError(bundle.getInt("code"));
                com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }

            @Override
            public void onSuccess(Bundle bundle) {

                JSONObject json = new JSONObject();
                try {
                    json.put("data", bundle.getString("data"));
                }catch (JSONException e){

                }
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setError(0);
                msgBuilder.setRespond(json.toString());
                com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        });
    }

}
